package com.allqj.qjf.service;

import com.allqj.qjf.config.DictServiceProperties;
import com.allqj.qjf.vo.ItemVO;
import com.allqj.qjf.vo.ResultVO;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sjw
 * @className DictService
 * @date 2021/8/22 11:03
 * @description: TODO
 */
public class CommonDict {
    private static DictServiceProperties DICTSERVICEPROPERTIES;
    private static RestTemplate RESTTEMPLATE;
    private static Map<Integer, List<ItemVO>> DICTCACHE;

    public static void init(DictServiceProperties dictServiceProperties) {
        System.out.println("---------------------------");
        DICTSERVICEPROPERTIES = dictServiceProperties;
        RESTTEMPLATE = new RestTemplate();
        DICTCACHE = new HashMap<>();
    }

    public static Object items(Integer dictType) {
        System.out.println("---------------------------");
        Object result = DICTCACHE.get(dictType);
        if (result != null) return result;
        System.out.println("远程获取");
        ResultVO resultVO=dictItems(dictType);
        //result = RESTTEMPLATE.getForObject(DICTSERVICEPROPERTIES.getServiceUrl() + "common/dict/" + dictType + "/item", String.class);
        DICTCACHE.put(dictType, resultVO.getResult());
        return result;
    }

    public static void updateCache(Integer dictType) {
        if (!DICTCACHE.containsKey(dictType)) return;
        System.out.println("更新缓存");
        ResultVO result=dictItems(dictType);
                //RESTTEMPLATE.getForObject(DICTSERVICEPROPERTIES.getServiceUrl() + "common/dict/" + dictType + "/item", String.class);
        DICTCACHE.put(dictType, result.getResult());
    }

    private static ResultVO dictItems(Integer dictType){
        ResultVO result = RESTTEMPLATE.getForObject(DICTSERVICEPROPERTIES.getServiceUrl() + "common/dict/" + dictType + "/item", ResultVO.class);
        return result;
    }

}
